const BaseIpcHandler = require('../BaseIpcHandler');
const axios = require('axios');
const { RemoteScriptInvoker } = require('../../remote/remoteScriptInvoker');

class RemoteAppControllerHandler extends BaseIpcHandler {
    async handle(event, params) {
        // 解析参数
        // console.log(`>> RemoteAppControllerHandler params = `, params);
        const { remoteId, operation } = params;

        // 业务逻辑
        let stdio, result = null;
        let invoker = new RemoteScriptInvoker(this.app, remoteId);
        try {
            if (operation === 'start') {
                if (await invoker.start()) {
                    result = { code: 0, msg: 'Start remote labelapp OK!' };
                } else {
                    result = { code: -1, msg: 'Start remote labelapp Failed!' };
                }
            } else if (operation == 'stop') {
                if (await invoker.stop()) {
                    result = { code: 0, msg: 'Stop remote labelapp OK!' };
                } else {
                    result = { code: -1, msg: 'Start remote labelapp Failed!' };
                }
            } else if (operation == 'init') {
                if (await invoker.init()) {
                    result = { code: 0, msg: 'Init remote labelapp OK!' };
                } else {
                    result = { code: -1, msg: 'Init remote labelapp Failed!' };
                }
            } else if (operation == 'monitor') {
                result = await invoker.monitor();
            } else if (operation == 'version') {
                stdio = await invoker.version();
                if (stdio) {
                    result = { code: 0, msg: stdio.trim() };
                } else {
                    result = { code: -1, msg: 'Get remote labelapp versions Failed!' };
                }
            }
        } catch (err) {
            console.error(`Remote labelapp controller invoke Failed!, Error =`, err);
            result = { code: -1, msg: err.msg };
        }

        // 返回结果
        // console.log(`RemoteAppControllerHandler result = `, result);
        if (event.from === 'localserver') {
            event.resp.send(result);
        } else {
            return result;
        }
    }
}

module.exports = RemoteAppControllerHandler;
